package spider

import (
	"encoding/json"

	"io/ioutil"
	"net/http"
	"priceApi/models"
	"priceApi/utils"
	"strconv"
	"strings"
	"time"
)

func HttpGet(url string) (*http.Response, error) {
	c := &http.Client{
		Timeout: 2 * time.Second,
	}
	return c.Get(url)
}

type JsonGDAX struct {
	Price string `json:"price"`
}

func GetGDAXData(symbol string) float64 {
	var jsondata JsonGDAX
	url := "https://api.gdax.com/products/" + symbol + "-USD/ticker"
	resp, err := HttpGet(url)

	//resp, err := utils.GetBySS(url)
	if err != nil {
		resp, err = utils.GetBySS(url)
		if err != nil {
			return 0
		}
	}
	defer resp.Body.Close()
	input, err := ioutil.ReadAll(resp.Body)
	if err != nil {
		return 0
	}
	json.Unmarshal([]byte(input), &jsondata)

	v2, _ := strconv.ParseFloat(jsondata.Price, 64)
	if v2 <= 0 {
		utils.SendToMail("GetGDAXData", "数据异常"+string(input))
	}
	return v2
}

type JsonKraken2 struct {
	C []string `json:"c"`
}
type JsonKraken1 struct {
	XLTCZUSD JsonKraken2 `json:"XLTCZUSD"`
	XETHZUSD JsonKraken2 `json:"XETHZUSD"`
	XXBTZUSD JsonKraken2 `json:"XXBTZUSD"`
	BCHUSD   JsonKraken2 `json:"BCHUSD"`
}
type JsonKraken struct {
	Result JsonKraken1 `json:"result"`
}

func GetKrakenData(symbol string) float64 {
	var jsondata JsonKraken
	var url string
	var price string
	if symbol == "BTC" {
		url = "https://api.kraken.com/0/public/Ticker?pair=XXBTZUSD"
	} else {
		url = "https://api.kraken.com/0/public/Ticker?pair=" + symbol + "USD"
	}

	resp, err := HttpGet(url)

	//resp, err := utils.GetBySS(url)
	if err != nil {
		resp, err = utils.GetBySS(url)
		if err != nil {
			return 0
		}
	}
	defer resp.Body.Close()
	input, err := ioutil.ReadAll(resp.Body)
	if err != nil {
		return 0
	}
	json.Unmarshal([]byte(input), &jsondata)

	if symbol == "BTC" {
		price = jsondata.Result.XXBTZUSD.C[0]
	} else if symbol == "ETH" {
		price = jsondata.Result.XETHZUSD.C[0]
	} else if symbol == "LTC" {
		price = jsondata.Result.XLTCZUSD.C[0]
	} else if symbol == "BCH" {
		price = jsondata.Result.BCHUSD.C[0]
	} else {
		price = "0"
	}
	v2, _ := strconv.ParseFloat(price, 64)
	if v2 <= 0 {
		utils.SendToMail("GetKrakenData", "数据异常"+string(input))
	}
	return v2
}

type JsonBitfinex struct {
	Price string `json:"last_price"`
}

func GetBitfinexData(symbol string) float64 {
	var jsondata JsonBitfinex

	symbol = strings.ToLower(symbol)

	url := "https://api.bitfinex.com/v1/pubticker/" + symbol + "usd"
	resp, err := HttpGet(url)

	//resp, err := utils.GetBySS(url)
	if err != nil {
		resp, err = utils.GetBySS(url)
		if err != nil {
			return 0
		}
	}
	defer resp.Body.Close()
	input, err := ioutil.ReadAll(resp.Body)
	//fmt.Println(string(input))
	if err != nil {
		return 0
	}
	json.Unmarshal([]byte(input), &jsondata)

	v2, _ := strconv.ParseFloat(jsondata.Price, 64)
	if v2 <= 0 {
		utils.SendToMail("GetBitfinexData", "数据异常"+string(input))
	}
	return v2
}

type JsonBitstamp struct {
	Price string `json:"last"`
}

func GetBitstampData(symbol string) float64 {
	var jsondata JsonBitstamp

	symbol = strings.ToLower(symbol)

	url := "https://www.bitstamp.net/api/v2/ticker/" + symbol + "usd"
	resp, err := HttpGet(url)

	//resp, err := utils.GetBySS(url)
	if err != nil {
		resp, err = utils.GetBySS(url)
		if err != nil {
			return 0
		}
	}
	defer resp.Body.Close()
	input, err := ioutil.ReadAll(resp.Body)
	//fmt.Println(input)
	if err != nil {
		return 0
	}
	json.Unmarshal([]byte(input), &jsondata)

	v2, _ := strconv.ParseFloat(jsondata.Price, 64)
	if v2 <= 0 {
		utils.SendToMail("GetBitstampData", "数据异常"+string(input))
	}
	return v2
}

type JsonGemini struct {
	Price string `json:"last"`
}

func GetGeminiData(symbol string) float64 {
	var jsondata JsonGemini

	symbol = strings.ToLower(symbol)

	url := "https://api.gemini.com/v1/pubticker/" + symbol + "usd"
	resp, err := HttpGet(url)

	//resp, err := utils.GetBySS(url)
	if err != nil {
		resp, err = utils.GetBySS(url)
		if err != nil {
			return 0
		}
	}
	defer resp.Body.Close()
	input, err := ioutil.ReadAll(resp.Body)
	if err != nil {
		return 0
	}
	json.Unmarshal([]byte(input), &jsondata)

	v2, _ := strconv.ParseFloat(jsondata.Price, 64)
	if v2 <= 0 && symbol != "ltc" {
		utils.SendToMail(symbol+"GetGeminiData", "数据异常"+string(input))
	}
	return v2
}

type TypeBuySell struct {
	Type int
	Buy  float64
	Sell float64
}

func GetExchangeData() {
	//fmt.Println(int(time.Now().Unix()))
	symbols := utils.GetSymbolsByConf()

	//rate := models.GetRateUSDT()
	over := models.GetOver()
	for _, value := range symbols {
		var exchange models.Exchange
		exchange.Symbol = value
		exchange.Gdax = GetGDAXData(value)

		//exchange.Bitfinex = GetBitfinexData(value)

		exchange.Bitstamp = GetBitstampData(value)

		exchange.Gemini = GetGeminiData(value)
		exchange.Kraken = GetKrakenData(value)
		exchange.Created = int(time.Now().Unix())

		models.InsertExchange(&exchange)

		var count int
		var sum float64

		if exchange.Gdax > 0 {
			count++
			sum = sum + exchange.Gdax
		}
		if exchange.Bitfinex > 0 {
			count++
			sum = sum + exchange.Bitfinex
		}
		if exchange.Bitstamp > 0 {
			count++
			sum = sum + exchange.Bitstamp
		}
		if exchange.Gemini > 0 {
			count++
			sum = sum + exchange.Gemini
		}
		if exchange.Kraken > 0 {
			count++
			sum = sum + exchange.Kraken
		}

		v1, _ := strconv.ParseFloat(strconv.FormatFloat(sum*(1+over)/float64(count), 'f', 2, 64), 64)

		models.InsertPrice(3, value, v1, v1)

		time.Sleep(time.Second * 2)

	}

	//fmt.Println(int(time.Now().Unix()))
}

//type JsonUWM struct {
//	New_price    float64 `json:"new_price"`
//	Highsandlows float64 `json:"highsandlows"`
//}

//func GetUWNWebPrice() {
//	var jsondata JsonUWM

//	url := "https://zh.urbewin.com/weinongtangWeb/getNewPriceByETH.do"
//	resp, err := http.Get(url)
//	if err != nil {
//		return
//	}
//	defer resp.Body.Close()
//	input, err := ioutil.ReadAll(resp.Body)
//	if err != nil {
//		return
//	}
//	json.Unmarshal([]byte(input), &jsondata)
//	ethprice := models.GetDataFromMydql("ETH")

//	models.InsertErc20coin("UWN", jsondata.New_price*ethprice.Buy, jsondata.Highsandlows)
//}
